package com.qf.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtUtils {
    public String createToken(Map map,String name){
        //设置头部部分
        Map header = new HashMap<>();
        header.put("alg","HS256");
        header.put("typ","JWT");
        //签名部分使用的服务器的私钥
        Algorithm algorithmHS = Algorithm.HMAC256("qianfengniubihahhaniubihahha");
        //载荷部分
        String sign = JWT.create().withHeader(header)
                .withIssuer("qiafneng")
                .withSubject("secret")
                .withIssuedAt(new Date())
                .withClaim("name", map.get(name).toString())

                .sign(algorithmHS);

        return sign;
    }

    public String  verfiyToken(String token){

        Algorithm algorithmHS = Algorithm.HMAC256("qianfengniubihahhaniubihahha");

        JWTVerifier qiafneng = JWT.require(algorithmHS).withIssuer("qiafneng").build();
        //进行验证
        DecodedJWT verify = qiafneng.verify(token);
        //获取 自定义的内容
        Claim name = verify.getClaim("name");

        return name.toString();
    }
}

